package com.sky.interceptor;

import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.exception.extend.LoginFailedException;
import com.sky.properties.JwtProperties;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenAdminInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties jwtProperties;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler){
        //首先判断当前拦截到的是Controller的方法还是其他资源
        if(!(handler instanceof HandlerMethod)){
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //获取员工id
      // Long id =(Long) request.getSession().getAttribute("employee");//强转到对应的类型的数据
        // 首先获取请求头的令牌数据
        try {
            String token = request.getHeader(jwtProperties.getAdminTokenName());
            //解析令牌
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
           // String empId = claims.get(JwtClaimsConstant.EMP_ID,String.class);
            Long empId =Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
            log.info("我已经成功校验,当前员工id为："+empId);
            //如果是本人登录的，那么我们将改id存入线程中
            BaseContext.setCurrentId(empId);
            //如果登录有数据，说明已经被登录，那么直接放行
            return true;
        } catch (Exception e) {
            /*response.setStatus(401);
            return false;*/
            throw new LoginFailedException(MessageConstant.ACCOUNT_LOGIN_FAILED);
        }
    }
}
